#include <vector>
#include <queue>

using std::queue;
using std::vector;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        queue<TreeNode*> q;
        vector<int> ret;
        if (root != nullptr) {
            q.push(root);
        }
        while (!q.empty()) {
            ret.push_back(q.front()->val);
            int size = q.size();
            TreeNode* tmp;
            while (size > 0) {
                tmp = q.front();
                q.pop();
                if (tmp->right != nullptr) {
                    q.push(tmp->right);
                }
                if (tmp->left != nullptr) {
                    q.push(tmp->left);
                }
                size--;
            }
        }
        return ret;
    }
};